package com.vlin.token.defaut;

import org.json.JSONObject;

import com.vlin.api.client.ApiClient;
import com.vlin.api.client.Method;
import com.vlin.api.client.Params;
import com.vlin.api.client.request.ParamsProducer;
import com.vlin.token.Token;
import com.vlin.token.TokenRefresher;
import com.vlin.token.convert.TokenConverter;
import com.vlin.token.convert.defaut.DefaultTokenConvert;

public class DefaultTokenRefresher implements TokenRefresher {
	
	private ApiClient apiClient;
	
	private TokenConverter tokenConverter = new DefaultTokenConvert();
	
	private ParamsProducer paramsProducer;

	@Override
	public Token refreshToken() {
		Params params = paramsProducer.produce(this.apiClient.getAPI());
		
		JSONObject result = apiClient.send("/v1.0/token", params, Method.GET);
		
		return tokenConverter.convert(result);
	}

	@Override
	public Token refreshToken(Token token) {
		Params params = paramsProducer.produce(this.apiClient.getAPI());
		JSONObject result = apiClient.send("/v1.0/token/" + token.getRefreshToken(), params, Method.GET);
		
		return tokenConverter.convert(result);
	}

	@Override
	public TokenRefresher getTokenRefresher() {
		
		return this;
	}

	@Override
	public void setApiClient(ApiClient apiClient) {
		this.apiClient = apiClient;
		
	}

	@Override
	public ApiClient getApiClient() {
		
		return this.apiClient;
	}

	@Override
	public void setParamsProduer(ParamsProducer paramsProducer) {
		if(paramsProducer != null) {
			this.paramsProducer = paramsProducer;
		}
		
	}

}
